const { promisify } = require('util')
const { resolve, dirname } = require('path')
const { writeFileSync, existsSync } = require('fs')

const download = promisify(require('download-git-repo'))

const { vueRepo } = require('../config/repo-config')
const { commandSpawn } = require('../utils/terminal')
const { compileEjs } = require('../utils/ejs-compile')
const { createDir } = require('../utils/utils')

/**
 * @description create 创建命令的 action 动作函数
 * @param {string} project 项目文件夹名
 * @param {array} others 其他参数
 */
const createAction = async (project, others) => {
  console.log('项目工程初始化~')
  // 1. 从远程下载模板
  console.log('clone templet~')
  await download(vueRepo, project, { clone: true })

  // 2. npm install
  console.log('npm install ~')
  const cmd = process.platform === 'win32' ? 'npm.cmd' : 'npm'  // windows上执行的命令是不一样的, 一般都是 .cmd 结尾，可以通过 where 查看脚本执行命令 -> where yarn
  await commandSpawn(cmd, ['install'], { cwd: `./${project}` })

  // 3. npm run dev
  console.log('npm run dev ~')
  await commandSpawn(cmd, ['run', 'dev'], { cwd: `./${project}` })
}

/**
 * @description 创建单文件组件 action
 * @param {string} componentName 单文件组件名
 * @param {string} dest 组件存放路径
 * @returns 
 */
const createCpnAction = async (componentName, dest, lang) => {
  const targetPath = resolve(dest, `${componentName}.vue`)

  if (existsSync(targetPath)) {
    console.log('文件已存在!')
    return
  }

  // 如果文件夹不存在，创建文件夹
  createDir(dirname(targetPath))

  try {
    const ejsData = {
      lang: 'ts',
      message: 'Hello World'
    }

    const result = await compileEjs('vue3-component.ejs', ejsData)
    writeFileSync(targetPath, result)
  } catch (error) {
    console.log(error)
  }
}

const addPageAction = (pageName, destination) => {
  const targetPath = resolve(dest)
}

module.exports = {
  createAction,
  createCpnAction,
  addPageAction
}